package com.woniu.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.entity.Bank;
import com.woniu.entity.response.ResponseEntity;
import com.woniu.entity.vo.BankVo;
import com.woniu.entity.vo.PageBank;
import com.woniu.exception.controllerException.BankAccountNotFoundException;
import com.woniu.exception.controllerException.MoneyOutOfRangeException;
import com.woniu.service.IBankService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hyl
 * @since 2022-08-28
 *  todo CrossOrigin 跨域请求的注解,可以统一弄一个过滤器
 *
 */
@RestController
@RequestMapping("/brain/bank")
@CrossOrigin(allowCredentials = "true", originPatterns = "*")
public class BankController {
    @Autowired
    private IBankService ibs;

    /**
     *  根据id查询账户
     * @param info 里面包含了银行账户id以及将要扣款的金额
     * @return 一个ResponseEntity
     */
    @PostMapping("/debit")
    public ResponseEntity searchBankAccount(@RequestBody BankVo info){
        Bank bankAccount = null;
        // 先查询账号是否存在
        if(info.getTargetBankId() != null && info.getTargetBankId() >0){
                bankAccount = ibs.selectBankById(info.getTargetBankId());
        }
        else {
            return ResponseEntity.fail(null,"传入的数据为空或数据违反约束");
        }
        // 账号存在的情况进行扣款
        BigDecimal leftMoney = null;
            leftMoney = ibs.debitMoney(bankAccount,info.getTargetDebitMoney());
        // 更新扣款后的金额
        bankAccount.setLeftMoney(leftMoney);
        ibs.updateBank(bankAccount);
        return ResponseEntity.success(null, "扣款成功");

    }

    /**
     *  mybatis-plus的分页查询
     * @Param info 数据承载类
     * @return
     */
    @PostMapping("/search")
    public ResponseEntity<?> getBankByPage(@RequestBody PageBank info){
        Page<Bank> page = ibs.getAnyBankAccountsWithPage(info.getPageNum(),info.getPageSize(), info.getBank());
        List infoList = new ArrayList();
        infoList.add(page.getRecords());
        infoList.add(page.getTotal());
        infoList.add(page.getPages());
        infoList.add(page.getCurrent());
        infoList.add(page.getSize());
        return ResponseEntity.success(infoList,"查询成功");
    }

    @PostMapping("/condition")
    public ResponseEntity<?> getWithCondition(@RequestBody Bank info){
        List<Bank> list = ibs.getBankByCondition(info);
        return ResponseEntity.success(list,"查询成功");
    }

    @PostMapping("/upload")
    public ResponseEntity<?> uploadBank(@RequestParam("file") MultipartFile file) throws Exception {
        ibs.batchImport(file.getOriginalFilename(),file);

        return ResponseEntity.success("success","上传成功");
    }
}
